//
//  MyCollectionTableView.m
//  1gene
//
//  Created by 1jiyin on 16/3/16.
//  Copyright © 2016年 1jiyin. All rights reserved.
//
//*******************我的收藏*******************
#import "MyCollectionTableView.h"
#import "CollectionModel.h"

@implementation MyCollectionTableView
-(instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
    if (self=[super initWithFrame:frame style:style]) {
        self.delegate=self;
        self.dataSource=self;
        self.tableFooterView=[UIView new];
        self.tableHeaderView=[UIView new];
        self.separatorStyle=UITableViewCellSeparatorStyleNone;
        self.showsVerticalScrollIndicator=NO;
         _dataArray=[NSMutableArray array];
        [self getMyHttpData];
    }
    return self;
}
//tabelView的代理
//tableView的代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    for (id subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    cell.backgroundColor=[UIColor whiteColor];
    
    CollectionModel *model=_dataArray[indexPath.row];
    //cell.userInteractionEnabled=NO;
    //用户头像
    UIImageView *headImageView=[[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 56, 56)];
    [headImageView sd_setImageWithURL:[NSURL URLWithString:model.user_info[@"avatar_url"]] placeholderImage:[UIImage imageNamed:@"155x155-1.png"]];
    headImageView.layer.cornerRadius=56/2.0;
    headImageView.layer.masksToBounds=YES;
    [cell.contentView addSubview:headImageView];
    
    
    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:model.user_info[@"avatar_url"]]];
    UIImage *myHeadImage=[UIImage imageWithData:data];
    headImageView.image=myHeadImage;
    
    
    
    //盖按钮
    UIButton *headImageBtn1=[UIButton buttonWithType:UIButtonTypeCustom];
    headImageBtn1.frame=headImageView.frame;
    [headImageBtn1 addTarget:self action:@selector(headImageBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:headImageBtn1];
    
    
    CGFloat height=(56-8)/3.0;
    //用户名
    UILabel *name=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(headImageView.frame)+8, 10, 80, height)];
    name.text=model.user_info[@"nikename"];
    name.textColor=[UIColor colorWithRed:87/255.0 green:194/255.0 blue:209/255.0 alpha:1];
    name.font=[UIFont systemFontOfSize:13];
    name.frame=CGRectMake(CGRectGetMaxX(headImageView.frame)+8, 10, [self calculateWidthWithLable:name], height);
    [cell.contentView addSubview:name];
    
    //性别
    UIImageView *sexImageView=[[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(name.frame)+2, 10, height, height)];
    [cell.contentView addSubview:sexImageView];
    NSInteger sexState=[model.user_info[@"sex"] integerValue];
    if (sexState==0) {
        sexImageView.image=[UIImage imageNamed:@"sex_man"];
    }else{
        sexImageView.image=[UIImage imageNamed:@"sex_woman"];
    }
//    UILabel *sex=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(name.frame)+2, 10, 10, height)];
//    sex.text=_dataArray[indexPath.row][@"sex"];
//    sex.textColor=[UIColor redColor];
//    sex.font=[UIFont systemFontOfSize:10];
//    [cell.contentView addSubview:sex];
    
    //标签
    UILabel *biaoqian=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(headImageView.frame)+8, CGRectGetMaxY(name.frame)+4, 40, height)];
    biaoqian.text=model.tag_name;
    biaoqian.textColor=[UIColor colorWithRed:87/255.0 green:194/255.0 blue:209/255.0 alpha:1];
    biaoqian.font=[UIFont systemFontOfSize:12];
    biaoqian.frame=CGRectMake(biaoqian.frame.origin.x, biaoqian.frame.origin.y, [self calculateWidthWithLable:biaoqian]+8, biaoqian.frame.size.height);
    biaoqian.layer.borderColor=[UIColor colorWithRed:87/255.0 green:194/255.0 blue:209/255.0 alpha:1].CGColor;
    biaoqian.layer.borderWidth=1.0;
    biaoqian.layer.cornerRadius=2.0;
    biaoqian.textAlignment=NSTextAlignmentCenter;
    [cell.contentView addSubview:biaoqian];
    
    //时间
    UILabel *time=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(headImageView.frame)+8, CGRectGetMaxY(biaoqian.frame)+4, 90, height)];
    time.text=model.created_at;
    time.textColor=[UIColor colorWithRed:87/255.0 green:194/255.0 blue:209/255.0 alpha:1];
    time.font=[UIFont systemFontOfSize:13];
    time.frame=CGRectMake(time.frame.origin.x, time.frame.origin.y, [time calculateWidthWithLable:time], time.frame.size.height);
    [cell.contentView addSubview:time];
    
    //帖子标题
    UILabel *topic=[[UILabel alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(time.frame), self.frame.size.width-5-5, 20)];
    topic.text=model.title;
    topic.textColor=[UIColor grayColor];
    topic.font=[UIFont systemFontOfSize:13];
    [cell.contentView addSubview:topic];
    
    //划线
    UIView *line=[[UIView alloc]initWithFrame:CGRectMake(0, (10+50+20+2)-0.5, self.frame.size.width, 0.5)];
    line.backgroundColor=[UIColor colorWithRed:87/255.0 green:194/255.0 blue:209/255.0 alpha:1];
    [cell.contentView addSubview:line];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 10+50+20+2;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionModel *model=_dataArray[indexPath.row];
    [self.myCollectionDelegate gotoTieBaXiangQing:model.topic_id];
}

-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//根据文字计算宽度和高度
-(CGFloat)calculateWidthWithLable:(UILabel *)label
{
    CGSize size=[label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:label.font,NSFontAttributeName, nil]];
    return size.width;
}

//头像按钮的响应
-(void)headImageBtnClick:(UIButton *)sender
{
    NSLog(@"头像");
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionModel *model=_dataArray[indexPath.row];
    [_dataArray removeObjectAtIndex:indexPath.row];
    [self deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    [self getCancelCollection:model.topic_id];
}


//获取个人信息
-(void)getMyHttpData
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];
    
    [manager GET:[NSString stringWithFormat:MyCollection,token] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.header endRefreshing];
        NSArray *arr=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"我的收藏=====%@",arr);
        _dataArray=[NSMutableArray array];
        if (arr) {
            for (NSDictionary *dic1 in arr) {
                CollectionModel *model=[[CollectionModel alloc]initWithDictionary:dic1[@"topic"]];
                model.topic_id=dic1[@"topic_id"];
                [_dataArray addObject:model];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self reloadData];
            });
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.header endRefreshing];
        NSLog(@"error====%@",error.localizedDescription);
    }];
    
}

//取消收藏
-(void)getCancelCollection:(NSString *)topicid
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];
    
    [manager DELETE:[NSString stringWithFormat:CancelCollection,token,topicid] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"取消收藏%@",dic);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error%@",error.localizedDescription);
    }];
}




/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
